package com.onlygx.dva.common.config;


import lombok.RequiredArgsConstructor;
import org.springframework.boot.web.servlet.ServletComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.annotation.Nonnull;

/**
 * 描述 : 解决跨域和部分映射问题
 *
 * @author GaoXiang
 * @version V1.1
 * @since 19-5-8
 */
@Configuration
@ServletComponentScan
@RequiredArgsConstructor
public class WebApiConfiguration implements WebMvcConfigurer {

    final UserInterceptor userInterceptor;

    /**
     * /api/**  需要登陆才能访问的接口，主要验证对象
     * /free/** 无需登陆
     * /out/**  对外服务提供的接口 网关校验签名
     * /open/** 对三方提供的接口 网关校验签名
     */
    private static final String[] excludePath =
            {        "/free/**"
                    ,"/out/**"
                    ,"/open/**"
                    ,"/druid/**"
                    ,"/swagger-ui.html"
                    ,"/doc.html"
                    ,"/webjars/**"
                    ,"/swagger-resources/**"
            };

    /*
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        // 解决swagger无法访问
        registry.addResourceHandler("/ip-developer/swagger-ui.html")
                .addResourceLocations("classpath:/META-INF/resources/");

        // 解决swagger的js文件无法访问
        registry.addResourceHandler("/ip-developer/webjars/**")
                .addResourceLocations("classpath:/META-INF/resources/webjars/");

    }*/

    @Override
    public void addInterceptors(@Nonnull InterceptorRegistry registry) {
        WebMvcConfigurer.super.addInterceptors(registry);
        registry.addInterceptor(userInterceptor)
                .addPathPatterns("/api/**")
                .excludePathPatterns(excludePath);
    }

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        WebMvcConfigurer.super.addCorsMappings(registry);
        registry.addMapping("/**")
                .allowedHeaders("*")
                .allowedMethods("*")
                .allowedOrigins("*")
                .allowCredentials(true);
    }
}
